document.addEventListener('DOMContentLoaded', function() {
    const sourceText = document.getElementById('sourceText');
    const translatedText = document.getElementById('translatedText');
    const sourceLang = document.getElementById('sourceLang');
    const targetLang = document.getElementById('targetLang');
    const translateBtn = document.getElementById('translateBtn');
    const switchLangBtn = document.getElementById('switchLang');

    // 从storage中恢复上次的语言选择
    chrome.storage.local.get(['sourceLang', 'targetLang'], function(result) {
        if (result.sourceLang) sourceLang.value = result.sourceLang;
        if (result.targetLang) targetLang.value = result.targetLang;
    });

    // 保存语言选择
    function saveLanguagePreferences() {
        chrome.storage.local.set({
            'sourceLang': sourceLang.value,
            'targetLang': targetLang.value
        });
    }

    // 切换语言
    switchLangBtn.addEventListener('click', function() {
        if (sourceLang.value === 'auto') return;
        const temp = sourceLang.value;
        sourceLang.value = targetLang.value;
        targetLang.value = temp;
        saveLanguagePreferences();
    });

    // 语言选择改变时保存
    sourceLang.addEventListener('change', saveLanguagePreferences);
    targetLang.addEventListener('change', saveLanguagePreferences);

    // 翻译功能
    async function translate() {
        const text = sourceText.value.trim();
        if (!text) return;

        translateBtn.disabled = true;
        translatedText.value = '正在翻译...';

        try {
            const from = sourceLang.value;
            const to = targetLang.value;
            
            // 使用Google翻译API
            const url = `https://translate.googleapis.com/translate_a/single?client=gtx&sl=${from}&tl=${to}&dt=t&q=${encodeURIComponent(text)}`;
            
            const response = await fetch(url);
            const data = await response.json();
            
            if (data && data[0]) {
                // 合并所有翻译片段
                const translatedText = data[0]
                    .map(item => item[0])
                    .filter(Boolean)
                    .join('');
                    
                document.getElementById('translatedText').value = translatedText;
            } else {
                translatedText.value = '翻译失败，请稍后重试';
            }
        } catch (error) {
            console.error('Translation error:', error);
            translatedText.value = '翻译服务暂时不可用，请稍后重试';
        } finally {
            translateBtn.disabled = false;
        }
    }

    // 点击翻译按钮
    translateBtn.addEventListener('click', translate);

    // 添加回车键支持
    sourceText.addEventListener('keydown', function(e) {
        // 如果按下回车键且没有按住Shift键（避免换行）
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault(); // 阻止默认的换行行为
            translate();
        }
    });
}); 